package org.lmind.example.common.web.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lmind.example.common.web.ApplicationContext;
import org.lmind.example.common.web.SessionContext;
import org.lmind.example.common.web.SessionContextAware;
import org.lmind.example.common.web.SessionContextManager;
import org.lmind.example.common.web.jsp.tag.Functions;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class GeneralHandlerInterceptor implements HandlerInterceptor {
	
	private ApplicationContext applicationContext;
	
	private SessionContextManager sessionContextManager;
	
	private String encoding = "utf-8";
	
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public void setSessionContextManager(SessionContextManager sessionContextManager) {
		this.sessionContextManager = sessionContextManager;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		
		Functions.setApplicationContext(applicationContext);
		
		HttpSession session = request.getSession();
		GeneralSessionContext sessionContext = (GeneralSessionContext)session.getAttribute(SessionContext.class.getName());
		if (sessionContext == null) {
			sessionContext = new GeneralSessionContext();
			sessionContext.setRequest(request);
			session.setAttribute(SessionContext.class.getName(), sessionContext);
		}
		sessionContextManager.bindCurrentThread(sessionContext);
		
		if (handler instanceof SessionContextAware) {
			((SessionContextAware)handler).setSessionContext(sessionContext);
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		sessionContextManager.cleanCurrentThread();
	}

}
